package com.gaoxk.shutdownfiter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

// 拦截所有请求（包括API、静态资源等）
//可以用kill pid 优雅关闭
@WebFilter(urlPatterns = "/*")
@Component
public class ShutdownFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(ShutdownFilter.class);
    // 停服开关：默认false（允许请求）
    private final AtomicBoolean isShuttingDown = new AtomicBoolean(false);

    // 活跃请求计数器：记录正在处理的请求数
    private final AtomicInteger activeRequests = new AtomicInteger(0);

    // 外部触发停服（如关闭钩子、控制接口）
    public void startShutdown() {
        isShuttingDown.set(true);
    }

    // 获取当前活跃请求数（用于优雅等待）
    public int getActiveRequests() {
        return activeRequests.get();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 1. 若已触发停服，拒绝新请求
        if (isShuttingDown.get()) {
            log.warn("已接收kill pid信号，服务升级中，请稍后重试");
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            httpResponse.setContentType("text/plain;charset=UTF-8");
            httpResponse.getWriter().write("服务升级中，请稍后重试");
            return;
        }

        // 2. 未停服：计数+1，继续处理请求
        activeRequests.incrementAndGet();
        try {
            // 放行请求（执行后续过滤器、Servlet、业务逻辑等）
            chain.doFilter(request, response);
        } finally {
            // 3. 无论请求成功/失败，计数-1
            activeRequests.decrementAndGet();
        }
    }
}